package com.aperos.android15;


import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class BarEdit extends Activity implements Runnable {
	Context context;
	
	static final int TIME_DIALOG_BEGIN = 0;
	static final int TIME_DIALOG_END = 1;

	private int latitudeE6 = 0;
	private int longitudeE6 = 0;
	private EditText nameEditText;
	private EditText addressEditText;
	private EditText priceBeerEditText;
	private EditText priceCocktailEditText;
	private Integer happyHourBeginHour;
	private Integer happyHourBeginMinute;
	private Integer happyHourEndHour;
	private Integer happyHourEndMinute;
	private EditText priceBeerHappyHourEditText;
	private EditText priceCocktailHappyHourEditText;
	private Button mPickTimeBegin;
	private Button mPickTimeEnd;
	private CheckBox mCheckBox;
	private LinearLayout happyHourDiv;
	private TextView infoLocation;
	private TextView lblAddress;
	
	private ProgressDialog dialog;
	
	private Bundle extras;
	
	String barName;
	Double barPriceBeer;
	String barAddress;
	Double barPriceCocktail;
	Double barPriceBeerHappyHour;
	Double barPriceCocktailHappyHour;

	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bar_edit);
		context = this;
		
		extras = getIntent().getExtras();
		
		infoLocation = (TextView) findViewById(R.id.info_localisation);
		lblAddress = (TextView) findViewById(R.id.lbl_address);
		
		nameEditText = (EditText) findViewById(R.id.edit_name);
		addressEditText = (EditText) findViewById(R.id.edit_address);
		priceBeerEditText = (EditText) findViewById(R.id.edit_price_beer);
		priceCocktailEditText = (EditText) findViewById(R.id.edit_price_cocktail);
		mPickTimeBegin = (Button) findViewById(R.id.happy_hour_begin_button);
		mPickTimeEnd = (Button) findViewById(R.id.happy_hour_end_button);
		priceBeerHappyHourEditText = (EditText) findViewById(R.id.edit_price_beer_happy_hour);
		priceCocktailHappyHourEditText = (EditText) findViewById(R.id.edit_price_cocktail_happy_hour);
		
		happyHourDiv = (LinearLayout) findViewById(R.id.happy_hour_div);
		
		if (extras != null && extras.get("edit").equals("edit")) {
			infoLocation.setVisibility(8);
			addressEditText.setVisibility(8);
			lblAddress.setVisibility(8);
		}
		
		mPickTimeBegin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_BEGIN);
            }
        });
		
		mPickTimeEnd.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_END);
            }
        });
		
		
		if (extras != null && extras.get("edit").equals("edit")) {
			// EDIT
			nameEditText.setText(Service.currentBar.getName());
			addressEditText.setText(Service.currentBar.getAddress());
			if (Service.currentBar.getPriceBeer() != null) {
				priceBeerEditText.setText(Service.currentBar.getPriceBeer().toString());
			}
			if (Service.currentBar.getPriceCocktail() != null) {
				priceCocktailEditText.setText(Service.currentBar.getPriceCocktail().toString());
			}
			if (Service.currentBar.getPriceBeerHappyHour() != null) {
				priceBeerHappyHourEditText.setText(Service.currentBar.getPriceBeerHappyHour().toString());
			}
			if (Service.currentBar.getPriceCocktailHappyHour() != null) {
				priceCocktailHappyHourEditText.setText(Service.currentBar.getPriceCocktailHappyHour().toString());
			}
			
			happyHourBeginHour = Service.currentBar.getHappyHourBeginHour();
			happyHourBeginMinute = Service.currentBar.getHappyHourBeginMinute();
			happyHourEndHour = Service.currentBar.getHappyHourEndHour();
			happyHourEndMinute = Service.currentBar.getHappyHourEndMinute();
			updateDisplay();
			
			
			latitudeE6 = Service.currentBar.getLatitudeE6();
			longitudeE6 = Service.currentBar.getLongitudeE6();
		} else {
			// ADD
			latitudeE6 = AperosPasChers.myLocationOverlay.getMyLocation().getLatitudeE6();
			longitudeE6 = AperosPasChers.myLocationOverlay.getMyLocation().getLongitudeE6();
		}

		mCheckBox = (CheckBox) findViewById(R.id.checkboxHappyHour);
		if (happyHourBeginHour != null && happyHourBeginMinute != null && happyHourEndHour != null && happyHourEndMinute != null) {
			mCheckBox.setChecked(true);
		}
		mCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					happyHourDiv.setVisibility(0);
				} else {
					happyHourDiv.setVisibility(8);
				}
			}
		});
		
		if (mCheckBox.isChecked()) {
			happyHourDiv.setVisibility(0);
		} else {
			happyHourDiv.setVisibility(8);
		}
		
		final Button button = (Button) findViewById(R.id.btn_save);
        button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				boolean flag = true;
				
				barName = nameEditText.getText().toString();
				if ("".equals(barName)) {
					flag = false;
					Toast.makeText(context, R.string.error_no_bar_name, 1000).show();
				}
				
				barPriceBeer = null;
				if (!"".equals(priceBeerEditText.getText().toString())) {
					barPriceBeer = Double.valueOf(priceBeerEditText.getText().toString());
				} else {
					flag = false;
					Toast.makeText(context, R.string.error_no_price_beer, 1000).show();
				}
				
				barAddress = null;
				if (!"".equals(addressEditText.getText().toString())) {
					barAddress = addressEditText.getText().toString();
				}
				
				
				barPriceCocktail = null;
				if (!"".equals(priceCocktailEditText.getText().toString())) {
					barPriceCocktail = Double.valueOf(priceCocktailEditText.getText().toString());
				}
				
				barPriceBeerHappyHour = null;
				if (!"".equals(priceBeerHappyHourEditText.getText().toString())) {
					barPriceBeerHappyHour = Double.valueOf(priceBeerHappyHourEditText.getText().toString());
				}
				if (mCheckBox.isChecked() && barPriceBeerHappyHour == null) {
					flag = false;
					Toast.makeText(context, R.string.error_no_price_beer_happy_hour, 1000).show();
				}
				
				barPriceCocktailHappyHour = null;
				if (!"".equals(priceCocktailHappyHourEditText.getText().toString())) {
					barPriceCocktailHappyHour = Double.valueOf(priceCocktailHappyHourEditText.getText().toString());
				}
				
				if (!mCheckBox.isChecked()) {
					happyHourBeginHour = null;
					happyHourBeginMinute = null;
					happyHourEndHour = null;
					happyHourEndMinute = null;
					barPriceBeerHappyHour = null;
					barPriceCocktailHappyHour = null;
				} else {
					if (happyHourBeginHour == null) {
						happyHourBeginHour = new Integer(0);
					}
					if (happyHourBeginMinute == null) {
						happyHourBeginMinute = new Integer(0);
					}
					if (happyHourEndHour == null) {
						happyHourEndHour = new Integer(0);
					}
					if (happyHourEndMinute == null) {
						happyHourEndMinute = new Integer(0);
					}
				}
				
				if (flag) {
					dialog = ProgressDialog.show(context, "", getString(R.string.dialog_save_bar), true);
					new Thread(BarEdit.this).start();
				}
				
			}
           
        });
	}
	
	@Override
	public void run() {
		try {
			if (extras != null && extras.get("edit").equals("edit")) {
				Service.currentBar.setAddress(barAddress);
				Service.currentBar.setName(barName);
				Service.currentBar.setPriceBeer(barPriceBeer);
				Service.currentBar.setPriceCocktail(barPriceCocktail);
				Service.currentBar.setHappyHourBeginHour(happyHourBeginHour);
				Service.currentBar.setHappyHourBeginMinute(happyHourBeginMinute);
				Service.currentBar.setHappyHourEndHour(happyHourEndHour);
				Service.currentBar.setHappyHourEndMinute(happyHourEndMinute);
				Service.currentBar.setPriceBeerHappyHour(barPriceBeerHappyHour);
				Service.currentBar.setPriceCocktailHappyHour(barPriceCocktailHappyHour);
				Service.editBar(Service.currentBar, context);
			} else {
				Service.currentBar = new Bar(latitudeE6, longitudeE6, barName, barAddress, barPriceBeer, barPriceCocktail,
						happyHourBeginHour, happyHourBeginMinute, happyHourEndHour, happyHourEndMinute, barPriceBeerHappyHour, barPriceCocktailHappyHour);
				Service.addBar(Service.currentBar, context);
			}
			
			Intent myIntent = new Intent(context, AperosPasChers.class);
			context.startActivity(myIntent);
		} catch (Exception e) {
	    	e.printStackTrace();
	    	mHandler.post(mUpdateResults);
	    }
	}
	
	final Handler mHandler = new Handler();

    final Runnable mUpdateResults = new Runnable() {
        public void run() {
        	dialog.dismiss();
        	displayError();
        }
    };
    
	public void displayError() {
		Toast.makeText(context, R.string.error_save_bar, 2000).show();
	}
	
	private TimePickerDialog.OnTimeSetListener mTimeSetListenerBegin =
	    new TimePickerDialog.OnTimeSetListener() {
			@Override
	        public void onTimeSet(TimePicker view, int hour, int minute) {
				happyHourBeginHour = hour;
				happyHourBeginMinute = minute;
	            updateDisplay();
	        }
	};
	
	private TimePickerDialog.OnTimeSetListener mTimeSetListenerEnd =
	    new TimePickerDialog.OnTimeSetListener() {
			@Override
	        public void onTimeSet(TimePicker view, int hour, int minute) {
				happyHourEndHour = hour;
				happyHourEndMinute = minute;
	            updateDisplay();
	        }
	};
	
	@Override
	protected Dialog onCreateDialog(int id) {
	    switch (id) {
		    case TIME_DIALOG_BEGIN:
		    	if (happyHourBeginHour == null) {
		    		happyHourBeginHour = new Integer(0);
		    	}
		    	if (happyHourBeginMinute == null) {
		    		happyHourBeginMinute = new Integer(0);
		    	}
		    	
		        return new TimePickerDialog(this, mTimeSetListenerBegin, happyHourBeginHour, happyHourBeginMinute, true);
			case TIME_DIALOG_END:
				if (happyHourEndHour == null) {
					happyHourEndHour = new Integer(0);
		    	}
		    	if (happyHourEndMinute == null) {
		    		happyHourEndMinute = new Integer(0);
		    	}
		        return new TimePickerDialog(this, mTimeSetListenerEnd, happyHourEndHour, happyHourEndMinute, true);
		}
	    return null;
	}
	
	private void updateDisplay() {
		mPickTimeBegin.setText(new StringBuilder()
	                .append(pad(happyHourBeginHour)).append("h ")
	                .append(pad(happyHourBeginMinute)).append("m"));
		mPickTimeEnd.setText(new StringBuilder()
        .append(pad(happyHourEndHour)).append("h ")
        .append(pad(happyHourEndMinute)).append("m"));
	}

	private static String pad(Integer c) {
		if (c == null) {
			return "00";
		} else if (c >= 10) {
	        return String.valueOf(c);
		} else {
	        return "0" + String.valueOf(c);
		}
	}

	
}
